package com.tanqing.ddd.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanqing.ddd.domain.domain.DomainEvent;
import com.tanqing.ddd.domain.domain.DomainEventListener;
import com.tanqing.ddd.domain.event.CheckInEvent;
import com.tanqing.ddd.domain.event.CheckOutSuccessEvent;
import com.tanqing.ddd.domain.event.PayedEvent;
import com.tanqing.ddd.web.entity.ParkingView;
import com.tanqing.ddd.web.mapper.ParkingViewMapper;
import com.tanqing.ddd.web.service.IParkingViewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zs
 * @since 2024-01-15
 */
@Service
public class ParkingViewServiceImpl extends ServiceImpl<ParkingViewMapper, ParkingView> implements IParkingViewService, DomainEventListener {

    @Override
    public void onEvent(DomainEvent event) {
        if (event instanceof CheckInEvent) {
            insert((CheckInEvent) event);
        } else if (event instanceof CheckOutSuccessEvent) {
            updateCheckOutSuccess((CheckOutSuccessEvent) event);
        } else if (event instanceof PayedEvent) {
            updatepay((PayedEvent) event);
        }
    }

    public void insert(CheckInEvent checkInEvent) {
        ParkingView parkingView = new ParkingView();
        parkingView.setPlate(checkInEvent.getPlate().getPlateNumber());
        parkingView.setCheckInTime(new Date());
        this.save(parkingView);
    }

    public void updateCheckOutSuccess(CheckOutSuccessEvent checkOutSuccessEvent) {
        ParkingView parkingView = getlast(checkOutSuccessEvent.getPlate().getPlateNumber());
        if (parkingView != null) {
            parkingView.setCheckOutTime(new Date());
            this.save(parkingView);
        }
    }

    public void updatepay(PayedEvent payedEvent) {
        ParkingView parkingView = getlast(payedEvent.getPlate().getPlateNumber());
        if (parkingView != null) {
            parkingView.setPayAmount(payedEvent.getAmount());
            parkingView.setPayTime(payedEvent.getDate());
            this.save(parkingView);
        }
    }


    public ParkingView getlast(String plateNumber) {
        QueryWrapper<ParkingView> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ParkingView::getPlate, plateNumber)
                .orderByDesc(ParkingView::getId)
                .last(" limit 1");
        List<ParkingView> parkingViews =
                this.baseMapper.selectList(queryWrapper);
        if (parkingViews != null && parkingViews.size() > 0) {
            return parkingViews.get(0);
        }
        return null;
    }
}
